import { handleActions as createReducer } from 'redux-actions'
import { fromJS, setIn, getIn, mergeDeep, removeIn, updateIn } from 'immutable'
import { 
  load_todo_success, 
  add_todo_success, 
  remove_todo_success, 
  modify_todo_success, 
  modify_filter_todo,
  clear_todo_success,
  modify_todo_edit_success,
  modify_todo_name_success
 } from '../action/todo.action'

const init = fromJS({
  todolist: [],
  filter: 'all'
})

export default createReducer({
  [load_todo_success]: (state, action) => {
    return setIn(state, ['todolist'], action.payload)
  },
  [add_todo_success]: (state,action) => {
    // mergeDeep 合并数组
    // 第二个参数， 是要合并的属性及被合并的值
    return mergeDeep(state, { todolist: [action.payload] })
  },
  [remove_todo_success]: (state,action) => {
    // 需要获取被删除项的 id
    let index = getIn(state, ['todolist']).findIndex(todolist => todolist.id === action.payload)
    // removeIn 
    return removeIn(state, ['todos', index])

  },
  [modify_todo_success]: (state, action) => {
    let index = getIn(state, ['todolist']).findIndex(todolist => todolist.id === action.payload.id)
    // updateIn  
    // 第二个参数是要更新的属性
    // 第三个参数就是我们要更新成的目标值
    return updateIn(state, ['todolist', index], () => action.payload)
  },
  [modify_filter_todo]: (state, aciton) => {
    return setIn(state, ['filter'], aciton.payload)
  },
  [clear_todo_success]: (state, action) => {
    let todolist = getIn(state, ['todolist'])
    todolist = todolist.filter(todo => !todo.isCompleted)
    return setIn(state, ['todolist'], todolist)
  },
  [modify_todo_edit_success]: (state, action) => {
    let index = getIn(state, ['todolist']).findIndex(todolist => todolist.id === action.payload.id)
    return updateIn(state, ['todolist', index], () => action.payload)
  },
  [modify_todo_name_success]: (state, action) => {
    let index = getIn(state,['todolist']).findIndex(todolist => todolist.id === action.payload.id)
    return updateIn(state, ['todolist', index], () => action.payload)
  }
}, init)

